<template>
	<view class="catgory-wrap">
		<!-- 标题栏 -->
		<view class="head-nav">
			<u-navbar backIconName borderBottom :background="navbar.background" :backTextStyle="navbar.backTextStyle" backText="分类">
				<view class="ma20" @tap="$Router.push({ path: '/pages/goods/list' })">
					<u-search placeholder="搜索" disabled v-model="keyword" :showAction="false" height="46"></u-search>
				</view>
			</u-navbar>
		</view>
		<view class="x-f wrapper-box">
			<!-- 左侧分类列表 -->
			<view class="u-tab-view menu-scroll-view">
				<view
					v-for="(item, index) in tabbarList"
					:key="index"
					class="u-tab-item"
					:class="[currentTab == index ? 'u-tab-item-active' : '']"
					:data-current="index"
					@tap="swichMenu(index)"
				>
					<text class="menu-name">{{ item.name }}</text>
				</view>
			</view>

			<!-- 右侧商品列表 -->
			<view class="right-wrap">
				<scroll-view v-if="goodsList.length" scroll-y class="right-box menu-scroll-view" scroll-with-animation :scroll-top="scrollTop" @scrolltolower="loadMore">
					<view v-if="tabbarList[currentTab].image" class="category-img-wrap x-c">
						<image class="category-img" :src="tabbarList[currentTab].image" mode="widthFix"></image>
					</view>
					<view class="category-title">{{ tabbarList[currentTab].name }}</view>

					<view class="sh-big-card-wrap ma20 " v-for="item in goodsList" :key="item.id">
						<view class="big-goods-card" @tap="jump('/pages/goods/detail/index', { id: item.id })">
							<view class="img-wrap mb20">
								<image class="goods-img" :src="item.image" mode="aspectFill"></image>
								<image class="goods-tag" v-if="item.is_hot && !item.activity" :src="$IMG_URL + '/goods/goods_hot_tag.png'" mode=""></image>
								<image class="goods-tag" v-if="item.activity" :src="tagPath[item.activity_type]" mode=""></image>
							</view>
							<view class="goods-title px20 mb10 more-t">{{ item.title }}</view>
							<view class="goods-time px20 mb20">{{ item.subtitle }}</view>
							<view class="u-m-b-20 px20" v-if="item.activity_discounts_tags.length">
								<view class="tag-box  u-m-r-10" v-for="(tag, index) in item.activity_discounts_tags" :key="index">{{ tag }}</view>
							</view>
							<view class="goods-progress px20 x-f mb10">
								<view class="cu-progress round sm">
									<view class="progress--ing" :style="[{ width: getProgress(item.sales, item.stock) }]"></view>
									<view class="round-tag" :style="[{ left: getProgress(item.sales, item.stock) }]">
										<image class="round-tag-img" :src="$IMG_URL + '/goods/goods_mini_hot.png'" mode=""></image>
									</view>
								</view>
								<view class="googs-send-num ml20">已售{{ item.sales }}件</view>
							</view>
							<view class="x-bc px20">
								<view class="price-box x-f">
									<view class="price">{{ item.price }}</view>
									<view class="origin-price ml10">￥{{ item.original_price }}</view>
								</view>
								<view class="cart-box">
									<!-- 单规格 -->
									<view class="" v-if="!item.activity">
										<view v-if="!item.is_sku">
											<button v-if="!isCart(item.id)" @tap.stop="addCart(item.sku_price[0])" class="cu-btn cart-btn">加入购物车</button>
											<view class="num-step" v-else>
												<uni-number-box
													@change="onChangeNum($event, item.sku_price[0])"
													:value="checkCart[item.id].num"
													:step="1"
													:min="0"
													:goodsInfo="item"
													:currentSkuPrice="item.sku_price[0]"
													:disabled="numberDisabled"
												></uni-number-box>
											</view>
										</view>
										<!-- 多规格 -->
										<button class="cu-btn item-btn sel-sku " @tap.stop="selSku(item)" v-else>选规格</button>
									</view>
									<button class="cu-btn item-btn sel-sku" v-else>立即抢购</button>
								</view>
							</view>
						</view>
					</view>
					<!-- 加载更多 -->
					<u-loadmore v-if="!isEmpty" height="80rpx" :status="loadStatus" icon-type="flower" color="#ccc" />
				</scroll-view>
				<!-- 空数据 -->
				<u-empty v-if="isEmpty" mode="list"></u-empty>
			</view>
		</view>
		<!-- 规格 -->
		<t-takeout-sku v-if="goodsInfo.id && showSku" v-model="showSku" :goodsInfo="goodsInfo" :buyType="'cart'"></t-takeout-sku>
		<!-- 登录提示 -->
		<t-login-modal></t-login-modal>
	</view>
</template>

<script>
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
export default {
	components: {},
	data() {
		return {
			navbar: {
				backTextStyle: {
					color: '#333',
					'font-size': '35rpx',
					'font-weight': '600'
				},
				background: {
					background: '#fff'
				}
			},
			showSku: false, //是否显示规格弹窗
			isEmpty: false,
			currentTab: 0,
			categoryID: 0, //分类id
			tabbarList: [], //左侧分类列表
			goodsList: [], //商品列表
			goodsInfo: {}, //点击商品详情
			numberDisabled: false, //购物车计数器
			loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
			currentPage: 1,
			lastPage: 1
		};
	},
	props: {},
	computed: {
		...mapState({
			cartNum: state => state.cart.cartNum,
			cartList: state => state.cart.cartList
		}),
		...mapGetters(['totalCount', 'isSel']),
		// 购物车检测
		checkCart() {
			let obj = {};
			this.cartList.forEach(item => {
				obj[item.goods_id] = {
					num: item.goods_num,
					cartOrderId: item.id
				};
			});
			return obj;
		}
	},
	async onLoad() {
	},
	async onShow() {
		let query = uni.getStorageSync('tab-/pages/index/category');
		let queryCategoryId = Number(query.id)
		if (this.categoryID != queryCategoryId) {
			this.categoryID = queryCategoryId;
			await this.getCategory();
			this.goodsList = [];
			await this.getGoodsList();
			this.getCartList();
		}
	},
	methods: {
		...mapActions(['getCartList', 'changeCartList', 'addCartGoods']),
		// 跳转详情
		toGoodDetail(id) {
			this.$Router.push({ path: '/pages/goods/detail/index', query: { id: id } });
		},

		// 百分比
		getProgress(sales, stock) {
			let unit = '';
			if (stock + sales > 0) {
				let num = (sales / (sales + stock)) * 100;
				unit = num.toFixed(2) + '%';
			} else {
				unit = '0%';
			}
			return unit;
		},

		// 加载更多
		loadMore() {
			if (this.currentPage < this.lastPage) {
				this.currentPage += 1;
				this.getGoodsList();
			}
		},

		// 获取分类
		async getCategory() {
			const res = await this.$api('category.info', {
				id: 0
			});
			if (res.code === 1) {
				const tabbarData = await this.$api('category.detail', {
					id: res.data.id
				});
				this.tabbarList = tabbarData.data.children;
				if (!this.categoryID) {
					this.categoryID = this.tabbarList[0]?.id;
				} else {
					for(var i in this.tabbarList) {
						if (this.tabbarList[i]['id'] == this.categoryID) {
							this.currentTab = i;
							break;
						}
					}
				}
			}
		},

		// 获取分类商品
		getGoodsList() {
			let that = this;
			that.loadStatus = 'loading';
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			that.$api('goods.lists', {
				category_id: that.categoryID,
				page: that.currentPage
			}).then(res => {
				uni.hideLoading();
				if (res.code === 1) {
					that.goodsList = [...that.goodsList, ...res.data.data];
					that.isEmpty = !that.goodsList.length;
					that.lastPage = res.data.last_page;
					that.loadStatus = that.currentPage < res.data.last_page ? 'loadmore' : 'nomore';
				}
			});
		},

		// 点击左边的栏目切换
		async swichMenu(index) {
			if (index == this.currentTab) return;
			this.currentTab = index;
			this.categoryID = this.tabbarList[index].id;
			uni.setStorageSync('tab-/pages/index/category', {id: this.categoryID});
			this.currentPage = 1;
			this.lastPage = 1;
			this.goodsList = [];
			await this.getGoodsList();
		},

		// 加入购物车
		addCart(goods) {
			if (goods.stock <= 0) {
				this.$tools.toast('库存不足');
				return;
			}
			let obj = {
				goods_id: goods.goods_id,
				goods_num: 1,
				sku_price_id: goods.id,
				goods_price: goods.price
			};
			let confirmGoodsList = {
				list: [obj],
				from: 'goods'
			};
			this.addCartGoods(confirmGoodsList).then(res => {
				if (res.code === 1) {
					this.$tools.toast(res.msg);
				}
			});
		},
		// 检测商品在购物车中的下标
		checkGoodsIndex(id) {
			let cIndex = 0;
			this.cartList.forEach((item, index) => {
				if (id == item.goods_id) {
					cIndex = index;
				}
			});
			return cIndex;
		},
		// 更改商品数
		async onChangeNum(e, goods) {
			let gIndex = this.checkGoodsIndex(goods.goods_id);
			if (e != this.checkCart[goods.goods_id].num) {
				this.numberDisabled = true;
				uni.showLoading({
					mask: true
				});
				if (e <= 0) {
					await this.changeCartList({ ids: [this.checkCart[goods.goods_id].cartOrderId], art: 'delete' });
				} else {
					this.$set(this.cartList[gIndex], 'goods_num', +e);
					await this.changeCartList({
						ids: [this.checkCart[goods.goods_id].cartOrderId],
						goodsNum: +e,
						art: 'change'
					});
				}
				this.numberDisabled = false;
				await uni.hideLoading();
			}
		},
		// 检测是否为购物车商品
		isCart(id) {
			let goodsId = id + '';
			return Object.keys(this.checkCart).includes(goodsId);
		},

		// 添加购物车
		async selSku(info) {
			this.goodsInfo = {};
			this.getGoodsDetail(info.id);
			this.showSku = true;
		},
		// 商品详情
		getGoodsDetail(id) {
			let that = this;
			that.$api('goods.detail', {
				id: id
			}).then(res => {
				if (res.code === 1) {
					that.goodsInfo = res.data;
				}
			});
		},

		// 路由跳转
		jump(path, parmas) {
			this.$Router.push({
				path: path,
				query: parmas
			});
		}
	}
};
</script>

<style lang="scss" scoped>
// 最外层结构包裹
.catgory-wrap {
	height: calc(100vh);
	/* #ifdef H5 */
	height: calc(100vh - var(--window-top));
	/* #endif */
	display: flex;
	flex-direction: column;
}
.wrapper-box {
	flex: 1;
	display: flex;
	overflow: hidden;
	// 左侧menu
	.u-tab-view {
		width: 200rpx;
		height: 100%;
		.u-tab-item {
			height: 110rpx;
			background: #f6f6f6;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 26rpx;
			color: #444;
			font-weight: 400;
			line-height: 1;
		}

		.u-tab-item-active {
			position: relative;
			color: #000;
			font-size: 30rpx;
			font-weight: bold;
			background: #fff;
		}

		.u-tab-item-active::before {
			content: '';
			position: absolute;
			border-left: 4px solid $t-mainColor;
			height: 32rpx;
			left: 0;
			top: 39rpx;
		}
	}
}

// 右侧商品滚动
.right-wrap {
	background-color: #fff;
	height: 100%;
	width: 100%;
	.category-img-wrap {
		margin: 20rpx;
		width: 554rpx;
		min-height: 200rpx;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 0 8rpx 2rpx rgba(199, 199, 199, 0.3);
		.category-img {
			width: 100%;
			background-color: #ccc;
			min-height: 200rpx;
			border-radius: 20rpx;
		}
	}
	.category-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #000;
		margin: 20rpx;
	}
	.right-box {
		height: 100%;
	}
}
.big-goods-card {
	background-color: #fff;
	border-radius: 20rpx;
	width: 100%;
	box-shadow: 0 0 8rpx 2rpx rgba(199, 199, 199, 0.3);
	padding-bottom: 10rpx;
	.img-wrap {
		position: relative;
		overflow: hidden;
		height: 256rpx;
		width: 100%;
		.goods-img {
			width: 100%;
			height: 256rpx;
			border-radius: 20rpx 20rpx 0 0;
			background-color: #ccc;
		}
		.goods-tag {
			position: absolute;
			top: 16rpx;
			left: 16rpx;
			width: 88rpx;
			height: 88rpx;
		}
	}
	.goods-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333333;
		line-height: 36rpx;
	}
	.goods-time {
		font-size: 24rpx;
		font-weight: 400;
		color: #999999;
		line-height: 36rpx;
	}
	.tag-box {
		border: 1px solid #ff0000;
		display: inline-block;
		font-size: 20rpx;
		line-height: 30rpx;
		padding: 0 10rpx;
		color: #ff0000;
		border-radius: 8rpx;
	}
	.goods-progress {
		.cu-progress {
			width: 200rpx;
			height: 20rpx;
			background: rgba(#ff6361, 0.2);
			overflow: visible;
			position: relative;
			.progress--ing {
				background: #ff6361;
				border-radius: 20rpx;
			}
			.round-tag {
				position: absolute;
				bottom: 0;
				width: 20rpx;
				height: 28rpx;
				margin-left: -10rpx;
				.round-tag-img {
					width: 20rpx;
					height: 28rpx;
				}
			}
		}
		.googs-send-num {
			font-size: 24rpx;
			font-weight: 400;
			color: #bebebe;
		}
	}
	.price-box {
		vertical-align: text-bottom;
		.price {
			font-size: 36rpx;
			color: $t-priceColor;
			font-weight: 600;
			&::before {
				content: '￥';
				font-size: 28rpx;
			}
			vertical-align: text-bottom;
		}
		.origin-price {
			vertical-align: text-bottom;
			font-size: 26rpx;
			font-weight: 400;
			text-decoration: line-through;
			color: #c4c4c4;
		}
	}
	.cart-box {
		.cart-btn,
		.sel-sku {
			width: 172rpx;
			height: 58rpx;
			background: linear-gradient(to right, $t-gradualColor, $t-mainColor);
			border-radius: 30rpx;
			padding: 0;
			font-size: 26rpx;
			font-weight: 500;
			color: #ffffff;
		}
	}
}
</style>
